<template>
	<view class="container">
		<block-view>
			<input class="main-title" type="text" v-model="formData.title" placeholder-class="placeholder-css" placeholder="为你的活动添加一个好听的主题" />
			<textarea class="desc" :maxlength="-1" placeholder="详细描述你的报名需求" placeholder-class="placeholder-css" v-model="formData.desc"></textarea>
			<!-- 活动图片 -->
			<view class="images-wrapepr">
				<form-title required title="添加活动介绍图片" note="(不超过9张)"></form-title>
				<view class="images-list">
					<view class="img-wrapper" v-for="(img, index) in images" :key="index">
						<uni-icons class="del-ico" type="minus-filled" :size="24" color="#dd524d"
							@click="delImage(index)"></uni-icons>
						<image class="img" :src="img.url" mode="aspectFill"></image>
						<view class="percent-mask" v-if="img.fail || img.progress < 100">
							<text v-if="!img.fail">{{ img.progress }}%</text>
							<text v-if="img.fail" @click="uploadAgain(index)">点击重试</text>
						</view>
					</view>
					<view class="add-btn" v-if="images.length < 9" hover-class="tap-hover" @click="addImage()">
						<uni-icons type="plusempty" :size="30" color="#02C9BF"></uni-icons>
					</view>
				</view>
			</view>
			<view class="ac-type">
				<form-title required title="选择活动类型"></form-title>
				<view class="radio-list">
					<view class="radio-item" :class="{'radio-active': formData.type == item.value}"
						v-for="(item, index) in typeData" :key="item.value" @click="formData.type = item.value">
						<view class="radio-mark">
							<uni-icons v-if="formData.type == item.value" type="checkmarkempty" :size="12" color="#fff"></uni-icons>
						</view>
						<view>{{ item.text }}</view>
					</view>
				</view>
			</view>
		</block-view>

		<block-view padding-top="0">
			<view class="ipt-item">
				<view class="ipt-title">活动地点</view>
				<input class="item-ipt" type="text" v-model="formData.address" placeholder-class="placeholder-css" placeholder="请填写活动地点(非必填)" />
				<uni-icons type="location" :size="24" color="#00CAC0" @click="chooseLoaction"></uni-icons>
			</view>
			<view class="ipt-item">
				<view class="ipt-title">报名日期</view>
				<uni-datetime-picker type="datetimerange" v-model="daterange" :hide-second="true">
					<input class="item-ipt" style="width: 100%;" :value="enroll_date" type="text" :disabled="true"
						placeholder="请选择报名日期(非必填)" placeholder-class="placeholder-css" />
				</uni-datetime-picker>
			</view>
			<view class="ipt-item">
				<view class="ipt-title">活动日期</view>
				<uni-datetime-picker type="datetimerange" v-model="activityDateRange" :hide-second="true">
					<input class="item-ipt" style="width: 100%;" type="text" :value="activity_date" :disabled="true"
						placeholder="请选择活动日期(非必填)" placeholder-class="placeholder-css" />
				</uni-datetime-picker>
			</view>
			<view class="ipt-item">
				<view class="ipt-title">数量</view>
				<input class="item-ipt" type="number" v-model="formData.people_num" placeholder-class="placeholder-css" placeholder="最大参与数(不填为无限制)" />
			</view>
			<view class="flex-column" v-if="formData.type != 3">
				<view class="ipt-title">宠物类型</view>
				<view class="radio-list">
					<view class="radio-item" :class="{'radio-active': formData.pet_type == item.value}"
						v-for="(item, index) in petData" :key="item.value" @click="formData.pet_type = item.value">
						<view class="radio-mark">
							<uni-icons v-if="formData.pet_type == item.value" type="checkmarkempty" :size="12"
								color="#fff"></uni-icons>
						</view>
						<view>{{ item.text }}</view>
					</view>
				</view>
			</view>
		</block-view>

		<block-view>
			<form-title title="添加活动费用" note="(非必填,最多添加三项,不填为免费)" margin-bottom="24rpx"></form-title>
			<view class="cost-item-wrapper" v-for="(item, index) in costList" :key="index">
				<view class="ipt-item cost-item">
					<view class="ipt-title">费用名称</view>
					<input class="item-ipt" type="text" v-model="item.name" placeholder-class="placeholder-css" placeholder="请输入费用名称" />
				</view>
				<view class="ipt-item cost-item">
					<view class="ipt-title">价格¥</view>
					<input class="item-ipt" type="digit" v-model="item.price" placeholder-class="placeholder-css" placeholder="请输入价格" />
				</view>
			</view>
			<view class="add-cost" @click="addCost()">
				<uni-icons type="plusempty" :size="20" color="#02C9BF"></uni-icons>
				<view>添加</view>
			</view>

		</block-view>

		<block-view padding-top="20">
			<form-title title="队员信息收集偏好"></form-title>
			<view class="text-area-wrapper">
				<text class="text-placeholder"
					v-if="!formData.like_member && !like_member_ipt">{{ `您期望收集哪些用户的信息？(非必填)\n例如：宠物年龄、品种、个人信息登。可自由进行填写，填写后在用户报名后显示` }}</text>
				<textarea class="desc" v-model="formData.like_member" @input="textAreaIpt"></textarea>
			</view>
		</block-view>
		<!-- 协议 -->
		<checkbox-group @change="checkChange">
			<view class="protocol-wrapper">
				<label class="label-check">
					<checkbox class="circle" style="transform: scale(0.8);" :value="1" :checked="isChecked"
					activeBackgroundColor="#00CAC0" icon-color="#fff"  />
					<text>已阅读并同意</text>
				</label>
				<text class="theme-color" @click="checkProto()">《See Wow服务协议》</text>
			</view>
		</checkbox-group>

		<fixed-footer>
			<primary-btn title="发起活动" @btnClick="publishEvent()"></primary-btn>
		</fixed-footer>
		
		<toast ref="toast"></toast>
		
		<uni-popup ref="noticePopup" type="center" :is-mask-click="false">
			<view class="notice-wrapper" >
				<view class="close-icon" @click="$popupChange(this, 'noticePopup')"><uni-icons type="closeempty" :size="18" color="#222"></uni-icons></view>
				<scroll-view class="notice" scroll-y="true" >
					<view class="main-content" v-html="profit_notice"></view>
				</scroll-view>
				<view class="notice-btn-wrapper">
					<button class="btn notice-btn" @click="submit">我已知晓并发起活动</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import proto from '@/common/protocol.js'
	import { getCurrentDate } from '../../common/utils'
	import formTitle from './form-title.vue'
	export default {
		components: {
			formTitle
		},
		data() {
			return {
				profit_notice: ``,
				like_member_ipt: false,
				isEdit: false, // 是否是编辑
				petIndex: 0,
				formData: {
					title: '',
					desc: '',
					imgs: [], // 活动图片, 提交时转为以逗号隔开的字符串
					type: 1, // 活动类型
					pet_type: 0, // 宠物类型
					address: '', // 活动地点
					activity_date_start: '', // 开始活动日期
					activity_date_end: '',  // 结束活动日期
					enroll_date_start: '', // 开始报名日期
					enroll_date_end: '', // 结束报名日期
					people_num: '', // 活动人数
					price_level: [], // 提交时转换为json字符串
					like_member: '', // 队员收集偏好
					lng: 0,  // 经度
					lat: 0,  // 纬度
				},
				images: [], // 图片临时路径
				online_imgs: [], // 上传成功的图片路径
				daterange: [],
				activityDateRange: [],
				enroll_date: '', // 报名日期
				activity_date: '', // 活动日期
				costList: [], // 费用列表
				memberDesc: '您期望收集哪些用户的信息？(非必填)\n例如：宠物年龄、品种、个人信息登。可自由进行填写，填写后在用户报名后显示',
				typeData: [{
						text: '宠物活动',
						value: 1
					},
					{
						text: '宠物友好',
						value: 2
					},
					{
						text: '宠物市集',
						value: 3
					},
					{
						text: '其他活动',
						value: 4
					}
				],
				petData: [{
						text: '猫猫',
						value: 1
					},
					{
						text: '狗狗',
						value: 2
					},
					{
						text: '不限',
						value: 3
					}
				],
				isChecked: false,
			}
		},
		onLoad() {
			const eventChannel = this.getOpenerEventChannel()
			eventChannel.on('editInfo', (data) => {
				this.isEdit = true
				this.formData = data.info
				this.online_imgs = data.info.imgs?.split(',') || []
				this.images = this.online_imgs.map(item => {
					return {
						url: item,
						progress: 100,
						fail: false
					}
				})
				this.daterange = [data.info.enroll_date_start.substring(0, data.info.enroll_date_start.lastIndexOf(':')), data.info.enroll_date_end.substring(0, data.info.enroll_date_end.lastIndexOf(':'))]
				this.activityDateRange = [data.info.activity_date_start.substring(0, data.info.activity_date_start.lastIndexOf(':')), data.info.activity_date_end.substring(0, data.info.activity_date_end.lastIndexOf(':'))]
				if (data.info.price_level) {
					this.costList = JSON.parse(data.info.price_level)
				}
			})
		},
		onReady() {
			this.profit_notice = proto.profitNotice
		},
		watch: {
			daterange: {
				handler(val) {
					// console.log(val);
					const now_d = new Date(getCurrentDate()).getTime(),
						enroll_s_d = new Date(val[0].replace(/\-/g,'/')).getTime(),  // 报名开始时间
						enroll_e_d = new Date(val[1].replace(/\-/g,'/')).getTime()  // 报名结束时间
					if (enroll_s_d < now_d && !this.isEdit) {
						uni.showToast({
							title: '报名时间不能小于当前时间',
							icon: 'none',
							duration: 3000
						})
						return
					}
					if (this.activityDateRange != false) {
						const activity_s_d = new Date(this.activityDateRange[1].replace(/\-/g,'/')).getTime() // 活动结束时间
						if (enroll_s_d > activity_s_d || enroll_e_d > activity_s_d) {
							uni.showToast({
								title: '报名时间不能在活动结束时间之后',
								icon: 'none',
								duration: 3000
							})
							return
						}
					}
					
					this.formData.enroll_date_start = val[0]+':00'
					this.formData.enroll_date_end = val[1]+':00'
					this.enroll_date = val[0].replace(/\-/g,'.') + '～' + val[1].replace(/\-/g,'.')
				}
			},
			activityDateRange: {
				handler(val) {
					if (this.daterange != false) {
						const a_end_d = new Date(val[1].replace(/\-/g,'/')).getTime(),  // 活动结束时间
							e_start_d = new Date(this.daterange[0].replace(/\-/g,'/')).getTime(), // 报名开始时间
							e_end_d = new Date(this.daterange[1].replace(/\-/g,'/')).getTime()
							 
						if (a_end_d < e_start_d || a_end_d < e_end_d) {
							uni.showToast({
								title: '活动结束时间不能在报名时间之前',
								icon: 'none',
								duration: 3000
							})
							return
						}
					}
					
					this.formData.activity_date_start = val[0]+':00'
					this.formData.activity_date_end = val[1]+':00'
					this.activity_date = val[0].replace(/\-/g,'.') + '～' + val[1].replace(/\-/g,'.')
				}
			}
		},
		methods: {
			publishEvent() {
				const b = this.verifyData()
				if (!b) {
					return
				}
				if (this.isChecked) {
					this.submit()
					return
				}
				this.checkProto()
			},
			async submit() {
				this.$refs.noticePopup.close()
				this.isChecked = true
				const b = this.verifyData()
				if (!b) {
					return
				}
				if (this.costList != false) {
					this.formData.price_level = []
					for await (let item of this.costList) {
						if (item.name && Number(item.price) > 0) {
							this.formData.price_level.push(item)
						}
					}
				}
				this.formData.price_level = this.formData.price_level != false ? JSON.stringify(this.formData.price_level) : ''
				// this.formData.price_level = JSON.stringify(this.formData.price_level)
				this.formData.imgs = this.online_imgs.join(',')
				if (!this.formData.people_num) {
					this.formData.people_num = 0
				}
				const res = await this.$request.post('/api/activity/create', this.formData)
				// console.log(res)
				if (res.code == 200) {					
					this.$refs.toast.show({
						title: `发起活动成功\n官方审核通过后展示`
					})
					if (this.isEdit) {
						// editType: 表示编辑
						uni.$emit('editSuccess', {
							editType: 1
						})
					}
					setTimeout(() => {
						uni.navigateBack()
					}, 1500)
				}
			},
			// 添加费用
			addCost() {
				if (this.costList.length == 3) {
					uni.showToast({
						title: '最多只能添加三项',
						icon: 'none'
					})
					return
				}
				const obj = {
					id: this.costList.length + 1,
					name: '',
					price: ''
				}
				this.costList.push(obj)
			},
			// 添加图片
			addImage() {
				const count = 9 - this.images.length
				uni.chooseMedia({
					count: count,
					mediaType: ['image'],
					success: async (res) => {
						let temp = []
						const oldLength = this.images.length
						const tempFilePaths = res.tempFiles
						for await (const item of tempFilePaths) {
							if (item.size / 1024 / 1024 > 10) {
								uni.showToast({
									title: '图片不能超过10MB',
									icon: 'none'
								})
							} else {								
								temp.push(item.tempFilePath)
								this.images.push({
									url: item.tempFilePath,
									fail: false,
									progress: 0
								})
							}
						}
						if (temp == false) {
							return
						}
						let j = 0
						for await (let item of temp) {
							try {
								const res = await this.$request.upload('/api/file/upload', {
									filePath: item
								}, {
									load: false,
								}, (progress) => {
									this.images[j + oldLength].progress = progress
								})
								if (res.code == 200) {
									this.online_imgs.push(res.data.url)
									this.images[j + oldLength].fail = false
									this.images[j + oldLength].progress = 100
								} else {
									this.images[j + oldLength].fail = true
									this.images[j + oldLength].progress = 0
								}
							} catch {
								this.images[j + oldLength].fail = true
								this.images[j + oldLength].progress = 0
							}
							j += 1
						}
						/* temp.forEach(async (item, index) => {
							try {
								const res = await this.$request.upload('/api/file/upload', {
									filePath: item
								}, {
									load: false,
								}, (progress) => {
									this.images[index + oldLength].progress = progress
								})
								if (res.code == 200) {
									this.online_imgs.push(res.data.url)
									this.images[index + oldLength].fail = false
									this.images[index + oldLength].progress = 100
								} else {
									this.images[index + oldLength].fail = true
									this.images[index + oldLength].progress = 0
								}
							} catch {
								this.images[index + oldLength].fail = true
								this.images[index + oldLength].progress = 0
							}
						}) */
						// console.log(this.images);
					}
				})
			},
			// 删除图片
			delImage(index) {
				this.images.splice(index, 1)
				this.online_imgs.splice(index, 1)
			},
			// 选择地点
			chooseLoaction() {
				uni.chooseLocation({
					success: (res) => {
						const { name, latitude, longitude } = res
						// console.log(res)
						this.formData.address = name
						this.formData.lng = longitude
						this.formData.lat = latitude
					}
				})
			},
			// 上传失败的图片点击重新上传
			uploadAgain(index) {
				this.images[index].fail = false			
				this.$request.upload('/api/file/upload',
				{
					filePath: this.images[index].url
				}, 
				{
					load: false,
				}, (progress) => {
					this.images[index].progress = progress
				}).then(res => {
					if (res.code == 200) {
						this.online_imgs.splice(index, 0, res.data.url)
						this.images[index].progress = 100
						this.images[index].fail = false
					} else {
						this.images[index].fail = true
						this.images[index].progress = 0
					}
				}).catch(err => {
					this.images[index].fail = true
					this.images[index].progress = 0
				})
			},
			textAreaIpt() {
				if (!this.like_member_ipt) {
					this.like_member_ipt = true
				}
			},
			checkChange(e) {
				const { value } = e.detail
				this.isChecked = value != false ? true : false
			},
			checkProto() {
				this.$refs.noticePopup.open()
			},
			// 验证必填项数据是否填写
			verifyData() {
				const {
					title,
					desc
				} = this.formData
				if (!title) {
					uni.showToast({
						title: '请填写活动主题',
						icon: 'none'
					})
					return false
				}
				if (!desc) {
					uni.showToast({
						title: '请填写报名需求',
						icon: 'none'
					})
					return false
				}
				if (this.online_imgs == false) {
					uni.showToast({
						title: '请添加活动图片',
						icon: 'none'
					})
					return false
				}
				return true
			}
		}
	}
</script>

<style>
	page {
		background-color: #f6f7f8;
	}
</style>
<style scoped lang="scss">
	.notice-wrapper {
		overflow: hidden;
		background-color: #fff;
		width: 680rpx;
		height: 1200rpx;
		position: relative;
		border-radius: 24rpx;
		.close-icon {
			position: absolute;
			right: 20rpx;
			top: 20rpx;
			z-index: 2;
		}
		.notice {
			height: 1100rpx;			
			box-sizing: border-box;
			
			.main-content {
				padding: 30rpx 48rpx;
			}
		}
		.notice-btn-wrapper {
			height: 100rpx;
			background-color: #fff;
			display: flex;
			justify-content: center;
			align-items: center;
			.notice-btn {
				font-size: 28rpx;
				height: 72rpx;
				line-height: 72rpx;
				width: 360rpx;
				text-align: center;
				background-color: $uni-color-primary;
				color: #fff;
				border-radius: 16rpx;
			}
		}
		
	}
	.container {
		padding: 28rpx;
		padding-bottom: 240rpx;

		.main-title {
			font-size: 30rpx;
			font-weight: 500;
			padding: 24rpx 20rpx;
			border-bottom: 1px solid $uni-border-color;
		}

		.desc {
			width: 100%;
			box-sizing: border-box;
			margin-top: 32rpx;
			border: 1px solid $uni-border-color;
			border-radius: 20rpx;
			height: 300rpx;
			font-size: 28rpx;
			padding: 12rpx 20rpx;
		}

		.text-area-wrapper {
			position: relative;
			width: 100%;

			.text-placeholder {
				position: absolute;
				top: 0;
				left: 0;
				right: 0;
				padding: 20rpx;
				font-size: 30rpx;
				color: #999;
				white-space: pre-line;
				word-wrap: break-word;
			}
		}

		.images-wrapepr,
		.ac-type {
			margin-top: 40rpx;
		}

		.ipt-item {
			width: 100%;
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 40rpx 0;
			border-bottom: 1px solid $uni-border-color;
			font-size: 30rpx;

			.ipt-title {
				max-width: 150rpx;
				font-weight: 500;
			}

			.item-ipt {
				width: calc(100% - 180rpx);
				box-sizing: border-box;
				text-align: right;
				font-size: 28rpx;
			}
		}

		.flex-column {
			padding: 32rpx 0;
			font-size: 30rpx;
			border-bottom: none;

			.ipt-title {
				max-width: 150rpx;
				font-weight: 500;
				margin-bottom: 32rpx;
			}
		}

		.add-cost {
			display: flex;
			justify-content: center;
			align-items: center;
			color: $uni-color-primary;
			padding: 24rpx 0;

			.del-text {
				color: $uni-color-error;
			}
		}

		.cost-item-wrapper {
			padding-bottom: 12rpx;
			border-bottom: 1px solid $uni-border-color;
		}

		.cost-item {
			padding: 20rpx 0;
			border-bottom: none;
		}

		.radio-list {
			display: grid;
			grid-template-columns: 1fr 1fr 1fr;
			row-gap: 20rpx;
			column-gap: 20rpx;
			padding-bottom: 5px;

			.radio-item {
				height: 60rpx;
				border-radius: 8px;
				background-color: #f6f6f6;
				border: 0.5px solid #f6f6f6;
				font-size: 28rpx;
				display: flex;
				justify-content: center;
				align-items: center;

				.radio-mark {
					width: 24rpx;
					height: 24rpx;
					border-radius: 50%;
					display: flex;
					justify-content: center;
					align-items: center;
					border: 1px solid #999;
					margin-right: 8rpx;
				}
			}

			.radio-active {
				background-color: rgba($color: $uni-color-primary, $alpha: 0.1);
				border-color: $uni-color-primary;

				.radio-mark {
					background-color: $uni-color-primary;
					border-color: $uni-color-primary;
				}
			}
		}

		.images-list {
			display: grid;
			grid-template-columns: 1fr 1fr 1fr;
			row-gap: 20rpx;
			column-gap: 20rpx;

			.add-btn {
				height: 208rpx;
				border-radius: 30rpx;
				background-color: #f6f6f6;
				overflow: hidden;
				display: flex;
				align-items: center;
				justify-content: center;
			}

			.img-wrapper {
				height: 208rpx;
				border-radius: 30rpx;
				// overflow: hidden;
				position: relative;

				.del-ico {
					position: absolute;
					top: 0;
					right: 0;
					z-index: 3;
				}

				.img {
					width: 100%;
					height: 100%;
					border-radius: 30rpx;
				}

				.percent-mask {
					position: absolute;
					top: 0;
					left: 0;
					right: 0;
					bottom: 0;
					background-color: rgba(0, 0, 0, .5);
					display: flex;
					justify-content: center;
					align-items: center;
					color: #fff;
					z-index: 2;
					border-radius: 30rpx;
				}
			}

		}
	}
	
	.protocol-wrapper {
		margin-top: 48rpx;
		width: 100%;
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 24rpx;
		.theme-color {
			color: $uni-color-primary;
		}
		.label-check {
			display: inline-flex;
			align-items: center;
		}
		
	}
	
	:deep(.placeholder-css) {
		color: #999;
		font-weight: normal;
	}
</style>